﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cos.Core.NHibernate;
using Cos.Core.NHibernate.Util;
using Cos.Module.Template.Data;
using Microsoft.Practices.Unity;
using NHibernate;
using NHibernate.Criterion;

namespace Cos.Module.Template.NHibernate
{
    public class PartRepository : RepositoryBase, IPartRepository
    {
        [InjectionConstructor]
        public PartRepository(ISessionFactory sessionFactory)
            : base(sessionFactory)
        {
        }

        public Core.Model.Template.Part GetPart(int partId)
        {
            var part = CurrentSession.Get<PartDataModel>(partId);

            if (part == null)
            {
                return null;
            }

            return part.ToPart();
        }

        public Core.Model.Template.Part GetPart(int templateId, string partName)
        {
            var part =
                this.CurrentSession.CreateCriteria<PartDataModel>().Add(Restrictions.Eq("TemplateId", templateId)).Add(
                    Restrictions.Eq("PartName", partName)).UniqueResult<PartDataModel>();

            if (part == null)
            {
                return null;
            }

            return part.ToPart();
        }

        public IEnumerable<Core.Model.Template.Part> GetParts(int templateId)
        {
            return this.CurrentSession.CreateCriteria<PartDataModel>().Add(Restrictions.Eq("TemplateId", templateId)).List<PartDataModel>().Select(p => p.ToPart());
        }

        public Core.Model.Template.Part SavePart(Core.Model.Template.Part part)
        {
            var partDataModel = this.CurrentSession.Get<PartDataModel>(part.Id).ToPartDataModel(part);

            this.CurrentSession.SaveOrUpdate(partDataModel);

            this.CurrentSession.Flush();

            return partDataModel.ToPart();
        }
    }
}
